package git.soulbgm.common.handle;

import git.soulbgm.common.Constant;
import git.soulbgm.common.TcpConnectMap;
import git.soulbgm.common.socket.TcpServer;
import git.soulbgm.utils.ByteUtil;
import git.soulbgm.utils.LogUtil;
import git.soulbgm.utils.SerializeUtil;
import git.soulbgm.utils.SpringBeanUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.lang.reflect.Method;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-10-17 13:39
 * @description
 */
@ChannelHandler.Sharable
public class TcpServerHandle extends SimpleChannelInboundHandler<ByteBuf> {

    private TcpServer tcpClient;

    private LogUtil log = new LogUtil(getClass());

    public TcpServerHandle(TcpServer tcpClient) {
        this.tcpClient = tcpClient;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (IdleState.READER_IDLE.equals(event.state())) {
                // 长期未收到服务端推送的消息
                // 可以选择重新连接
//                tcpClient.doConnect();
            } else if (IdleState.WRITER_IDLE.equals(event.state())) {
                // 长期未向服务端推送消息
                // 发送心跳包
//                ctx.channel().writeAndFlush(ByteUtil.stringToByteBuf("111222333$_$"));
            } else if (IdleState.ALL_IDLE.equals(event.state())) {
                // 长期未收到服务端推送的消息并且也长期未向服务端推送消息
            }
        }
    }

    /**
     * 当客户端连接上来时调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String channelId = channel.id().asLongText();
        TcpConnectMap.put(channelId, channel);
    }

    /**
     * 当客户端连接断开时调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        Channel channel = ctx.channel();
        byte[] bytes = ByteUtil.byteBufToByteArray(msg);
        String channelId = channel.id().asLongText();
//        SerializeUtil.deserializer(bytes, ConsumerService.class);
    }



}
